package com.ringtheweb.service.impl;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ringtheweb.model.Role;
import com.ringtheweb.model.RoleType;
import com.ringtheweb.model.User;
import com.ringtheweb.model.UserStatus;
import com.ringtheweb.model.UserStatusType;
import com.ringtheweb.persistence.dao.IRoleDAO;
import com.ringtheweb.persistence.dao.IUserDAO;
import com.ringtheweb.service.IUserManager;
import com.ringtheweb.service.exception.NonUniqueLoginException;
import com.ringtheweb.service.exception.RoleNotFoundException;

/**
 * Manager for {@link User} related operations.
 * @author ldewavri
 *
 */
@Service("userManager")
public class UserManager implements IUserManager {
	
	private Log LOG = org.apache.commons.logging.LogFactory.getLog(UserManager.class);
	
	
	private IUserDAO userDAO;
	
	private IRoleDAO roleDAO;
	
	
	@Autowired
	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Autowired
	public void setRoleDAO(IRoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}


	/**
	 * {@inheritDoc}
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public User saveUserInRole(User user, RoleType roleType) throws NonUniqueLoginException,RoleNotFoundException {
		
		if (LOG.isDebugEnabled()) {
			LOG.debug("About to persist user " +user);
		}
		
		User dbUser = userDAO.findByLogin(user.getLoginName());
		if (dbUser != null) {
			throw new NonUniqueLoginException(String.format("User with login '%s' already exists ",
					user.getLoginName()));
		}
		
		Role role = roleDAO.findByName(roleType.name());
		if (role == null) {
			throw new RoleNotFoundException(String.format("Role '%s' can not be found ",roleType.name()));
		}
		
		
		if (roleType == RoleType.ADMIN) {
			user.setStatus(new UserStatus(UserStatusType.APPROVED));
		}
		else {
			user.setStatus(new UserStatus(UserStatusType.TO_BE_APPROVED));	
		}
		user.getRoles().add(role);
		
		User persistedUser = userDAO.makePersistent(user);
		return persistedUser;
	}

}
